<?php
/**
 * Created by PhpStorm.
 * User: luoshuqi
 * Date: 19-2-18
 * Time: 下午4:12
 */

namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use App\Models\SysAction;
use App\Models\SysLog;
use App\Models\SysOperation;
use App\Models\SysUser;

class SysLogController extends Controller
{
    /**
     * @operation(操作日志, 查看, 20000)
     */
    public function get()
    {
        $time = $this->filter('time');
        $query = SysLog::query();
        if ($time) {
            $time[1] .= ' 23:59:59';
            $query->whereBetween('created_at', $time);
        }

        $username = $this->filter('username');
        if ($username) {
            $userIds = SysUser::query()->where('username', 'like', "%$username%")->pluck('id');
            if (!$userIds) {
                return $this->ok(['total' => 0, 'list' => []]);
            }
            $query->whereIn('user_id', $userIds);
        }

        $total = $query->count();
        $list = $query->with('user:id,username')->forPage(...$this->page())->orderByDesc('id')->get();

        foreach ($list as &$v) {
            if ($v['action'] === 'IndexController@alterPassword') {
                $v['action'] = '修改密码';
            } else {
                $actionId = SysAction::query()->where('action', $v['action'])->value('id');
                if ($actionId) {
                    $rows = SysOperation::query()
                        ->where('actions', 'REGEXP', "\b$actionId\b")
                        ->selectRaw('CONCAT(`group`, " > ", name) action')
                        ->get()->toArray();

                    if ($rows) {
                        $rows = array_column($rows, 'action');
                        $v['action'] = implode(' 或 ', $rows);
                    }
                }
            }
        }
        unset($v);

        return $this->ok(['total' => $total, 'list' => $list]);
    }
}